/* eslint-disable */
// @ts-nocheck
import { UPNG } from "./UPNG";
//import { Message } from "element-ui";
const blobImgLoaderCanvas = document.createElement("canvas");
let blobImgLoaderLastImageIdDrawn;

let imageLoaders = {
  //for getSingleDCMImage api
  blobLoader(imageId) {
    let url = imageId
      .replace("blobLoader:", "")
      .replace(/ww[^&]+(&)?/g, "")
      .replace(/wl[^&]+(&)?/g, "")
      .replace(/intercept[^&]+(&)?/g, "")
      .replace(/cps[^&]+(&)?/g, "")
      .replace(/rps[^&]+(&)?/g, "")
      .replace(/pixelSpacing[^&]+(&)?/g, "")
      .replace(/&$/g, "");

    let wl,
      ww,
      columnPixelSpacing,
      rowPixelSpacing,
      intercept,
      orientation,
      origins,
      invert,
      max,
      min;
    imageId.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => {
      if (k === "ww") {
        ww = v.split("\\")[0];
      } else if (k === "wl") {
        wl = v.split("\\")[0];
      } else if (k === "pixelSpacing") {
        [columnPixelSpacing, rowPixelSpacing] = v.split("\\");
        isNaN(rowPixelSpacing) && (rowPixelSpacing = columnPixelSpacing)
      } else if (k === "rps") {
        rowPixelSpacing = v;
      } else if (k === "intercept") {
        intercept = v;
      } else if (k === "orientation") {
        orientation = v;
      } else if (k === "origin") {
        origins = v.split(",");
      } else if (k === "invert") {
        if (v === "undefined" || v === "false") {
          invert = false;
        } else if (v === "true") {
          invert = true;
        }
      }
    });
    let xhr = new XMLHttpRequest();
    xhr.timeout = 60000
    const promise = new Promise(function (resolve, reject) {
      xhr.open("get", url, true);
      xhr.responseType = "arraybuffer";
      xhr.onreadystatechange = function (oEvent) {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let responseAsArrayBuffer = xhr.response;
            let byteArray = new Int8Array(responseAsArrayBuffer);
            let png = UPNG.decode(byteArray);
            if (png.depth === 16) {
              png.data = u8tou16(png);
            }
            resolve(getImage(png));
            byteArray = null;
          } else {
            reject(xhr.statusText);
            //Message.closeAll();
            //Message.error("影像获取有误，请稍后再试！");
            console.log("download failed: " + xhr.statusText);
          }
        }
      };
      xhr.send();
    });
    const cancelFn = () => {
      xhr.abort();
    };
    return {
      promise,
      cancelFn,
    };

    function u8tou16(png) {
      //let start = new Date().getTime()
      let raw8bit = png.data;
      let len = png.height * png.width * 2;
      let buf = new ArrayBuffer(len); // 2 bytes for each char
      let bufView = new Int16Array(buf);
      let index = 0;
      min = bufView[0];
      max = bufView[0];
      for (let i = 0; i < len; i += 2) {
        let lower = raw8bit[i + 1];
        let upper = raw8bit[i];
        bufView[index] = lower + (upper << 8)// - 32768;
        bufView[index] < min ? (min = bufView[index]) : (min = min);
        //bufView[index] > max ? (max = bufView[index]) : (max = max);
        index++;
      }
      //减去最小值
      for (let j = 0; j < bufView.length; j++) {
        bufView[j] -= min;
      }
      min = bufView[0];
      max = bufView[0];
      for(let i = 0; i < bufView.length; i++){
        bufView[i] < min ? (min = bufView[i]) : (min = min);
        bufView[i] > max ? (max = bufView[i]) : (max = max);
      }
      intercept = 0;
      //console.log("Time:",new Date().getTime() - start)
      return bufView;
    }

    function getImage(png) {
      const width = png.width;
      const height = png.height;
      let image = {
        imageId: imageId
          .replace(/ww[^&]+(&)?/g, "")
          .replace(/wl[^&]+(&)?/g, "")
          .replace(/intercept[^&]+(&)?/g, "")
          .replace(/pixelSpacing[^&]+(&)?/g, "")
          .replace(/&$/g, ""),
        minPixelValue: 0,
        maxPixelValue: 255,
        slope: 1.0,
        intercept: 0,
        windowCenter: +wl,
        windowWidth: +ww,
        actualwindowCenter: +wl,
        actualwindowWidth: +ww,
        depth: png.depth,
        getPixelData: () => png.data,
        rows: height,
        columns: width,
        height: height,
        width: width,
        //color: false,
        columnPixelSpacing: +columnPixelSpacing,
        rowPixelSpacing: +rowPixelSpacing,
        sizeInBytes: width * height,
        invert: invert || false,
        colormap: 'gray'
      };
      if (png.depth === 16) {
        image.minPixelValue = +min;
        image.maxPixelValue = +max;
        image.intercept = +intercept;
        image.sizeInBytes = width * height * 2;
        image.windowCenter = +wl;
        image.windowWidth = +ww;
      }
      return image;
    }
  },
  blobImgLoaderNew(imageId) {
    let url = imageId
      .replace("blobImgLoader:", "")
      .replace(/cps[^&]+(&)?/g, "")
      .replace(/rps[^&]+(&)?/g, "")
      .replace(/intercept[^&]+(&)?/g, "")
      .replace(/windowLevel[^&]+(&)?/g, "")
      .replace(/orientation[^&]+(&)?/g, "")
      .replace(/origin[^&]+(&)?/g, "");
    if (url.indexOf("_16_") > -1) {
      url = url
        .replace(/_16_/g, "")
        .replace(/windowLevel[^&]+(&)?/g, "")
        .replace(/&$/g, "");
    } else {
      url = url.replace(/_8_/g, "").replace(/&$/g, "");
    }

    let wl,
      ww,
      columnPixelSpacing,
      rowPixelSpacing,
      intercept,
      orientation,
      origins,
      invert,
      max,
      min,
      sliceOrigin,
      sliceSpacing;
    imageId.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => {
      if (k === "windowLevel") {
        [ww, wl] = v.split(",");
      } else if (k === "cps") {
        columnPixelSpacing = v;
      } else if (k === "rps") {
        rowPixelSpacing = v;
      } else if (k === "intercept") {
        intercept = v;
      } else if (k === "orientation") {
        orientation = v;
      } else if (k === "origin") {
        origins = v.split(",");
      } else if (k === "invert") {
        if (v === "undefined" || v === "false") {
          invert = false;
        } else if (v === "true") {
          invert = true;
        }
      }
    });
    let xhr = new XMLHttpRequest();
    const promise = new Promise(function (resolve, reject) {
      xhr.open("get", url, true);
      xhr.responseType = "arraybuffer";
      xhr.onreadystatechange = function (oEvent) {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            sliceSpacing = xhr.getResponseHeader('slice-spacing').split(',').map(it => Number(it));
            sliceOrigin = xhr.getResponseHeader('slice-origin').split(',').map(it => Number(it));
            let responseAsArrayBuffer = xhr.response;
            let byteArray = new Uint8Array(responseAsArrayBuffer);
            let png = UPNG.decode(byteArray);
            if (png.depth === 16) {
              png.data = u8tou16(png);
            }
            resolve(getImage(png));
            byteArray = null;
          } else {
            reject(xhr.statusText);
            //Message.closeAll();
            //Message.error("影像获取有误，请稍后再试！");
            console.log("download failed: " + xhr.statusText);
          }
        }
      };
      xhr.send();
    });
    const cancelFn = () => {
      xhr.abort();
    };
    return {
      promise,
      cancelFn,
    };
    function u8tou16(png) {
      let raw8bit = png.data;
      let len = png.height * png.width * 2;
      let buf = new ArrayBuffer(len); // 2 bytes for each char
      let bufView = new Uint16Array(buf);
      let index = 0;
      min = bufView[0];
      max = bufView[0];
      for (let i = 0; i < len; i += 2) {
        let lower = raw8bit[i + 1];
        let upper = raw8bit[i];
        bufView[index] = lower + (upper << 8);
        bufView[index] < min ? (min = bufView[index]) : min;
        bufView[index] > max ? max = bufView[index] : max
        index++;
      }
      return bufView;
    }

    function getImage(png) {
      const width = png.width;
      const height = png.height;
      let image = {
        imageId: url
          .replace(/cps[^&]+(&)?/g, "")
          .replace(/rps[^&]+(&)?/g, "")
          .replace(/intercept[^&]+(&)?/g, "")
          .replace(/windowLevel[^&]+(&)?/g, "")
          .replace(/&$/g, ""),
        minPixelValue: 0,
        maxPixelValue: 255,
        slope: 1.0,
        intercept: 0,
        windowCenter: 127,
        windowWidth: 255,
        actualwindowCenter: +wl,
        actualwindowWidth: +ww,
        depth: png.depth,
        getPixelData: () => png.data,
        rows: height,
        columns: width,
        height: height,
        width: width,
        //color: false,
        columnPixelSpacing: +sliceSpacing[0],
        rowPixelSpacing: +sliceSpacing[1],
        sizeInBytes: width * height,
        invert: invert || false,
        sliceOrigin: sliceOrigin,
        sliceSpacing: sliceSpacing
      };
      if (png.depth === 16) {
        image.minPixelValue = +min;
        image.maxPixelValue = +max;
        image.intercept = +intercept;
        image.sizeInBytes = width * height * 2;
        image.windowCenter = +wl;
        image.windowWidth = +ww;
      }
      return image;
    }
  },
  blobImgLoader(imageId) {
    let url = imageId
      .replace("blobImgLoader:", "")
      .replace(/cps[^&]+(&)?/g, "")
      .replace(/rps[^&]+(&)?/g, "")
      .replace(/&$/g, "");
    let wl,
      ww,
      columnPixelSpacing,
      rowPixelSpacing,
      intercept = 0;

    imageId.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => {
      if (k === "windowLevel") {
        [ww, wl] = v.split(",");
      } else if (k === "cps") {
        columnPixelSpacing = v;
      } else if (k === "rps") {
        rowPixelSpacing = v;
      } else if (k === "intercept") {
        intercept = v;
        url = url
          .replace(/intercept[^&]+(&)?/g, "")
          .replace(/windowLevel[^&]+(&)?/g, "")
          .replace(/&$/g, "");
      }
    });

    return new Promise(function (resolve, reject) {
      let img = new Image();
      img.src = url;
      // img.crossOrigin = "Anonymous"
      img.onload = function () {
        resolve(
          getImage(
            img,
            imageId,
            +ww,
            +wl,
            +columnPixelSpacing,
            +rowPixelSpacing
          )
        );
      };
      img.onerror = function () {
        reject(new Error("{ src: url }"));
      };
    });

    function getImage(
      image,
      imageId,
      ww,
      wl,
      columnPixelSpacing,
      rowPixelSpacing
    ) {
      const width = image.naturalWidth;
      const height = image.naturalHeight;
      console.log(width, height);

      function getPixelData() {
        const imageData = getImageData();
        return imageData.data;
      }
      function getImageData() {
        let context;
        if (blobImgLoaderLastImageIdDrawn === imageId) {
          context = blobImgLoaderCanvas.getContext("2d");
        } else {
          blobImgLoaderCanvas.height = height;
          blobImgLoaderCanvas.width = width;
          context = blobImgLoaderCanvas.getContext("2d");
          context.drawImage(image, 0, 0);
          blobImgLoaderLastImageIdDrawn = imageId;
        }
        return context.getImageData(0, 0, width, height);
      }
      function getCanvas() {
        if (blobImgLoaderLastImageIdDrawn === imageId) {
          return blobImgLoaderCanvas;
        }
        blobImgLoaderCanvas.height = height;
        blobImgLoaderCanvas.width = width;
        const context = blobImgLoaderCanvas.getContext("2d");
        context.drawImage(image, 0, 0);
        blobImgLoaderLastImageIdDrawn = imageId;
        return blobImgLoaderCanvas;
      }

      return {
        // imageId: imageId,
        imageId: url.replace(/windowLevel[^&]+(&)?/g, ""),
        minPixelValue: 0,
        maxPixelValue: 255,
        slope: 1,
        intercept: intercept,
        windowCenter: wl,
        windowWidth: ww,
        render: cornerstone.renderWebImage,
        getPixelData,
        getCanvas,
        getImage: () => image,
        rows: height,
        columns: width,
        height: height,
        width: width,
        color: true,
        rgba: false,
        columnPixelSpacing: columnPixelSpacing,
        rowPixelSpacing: rowPixelSpacing,
        invert: false,
        sizeInBytes: width * height * 4,
      };
    }
  },
  blobLoaderMip(imageId) {
    let url = imageId
    .replace("blobLoaderMip:", "")
    .replace(/pixelSpacing[^&]+(&)?/g, "")
    .replace(/&$/g, "")
    /*.replace(/ww[^&]+(&)?/g, "")
    .replace(/wl[^&]+(&)?/g, "")
    .replace(/intercept[^&]+(&)?/g, "")
    .replace(/cps[^&]+(&)?/g, "")
    .replace(/rps[^&]+(&)?/g, "")*/

    let wl,
      ww,
      columnPixelSpacing,
      rowPixelSpacing,
      intercept,
      orientation,
      origins,
      invert,
      max,
      min;
    imageId.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => {
      if (k === "windowwidth") {
        ww = v.split("\\")[0];
      } else if (k === "windowlevel") {
        wl = v.split("\\")[0];
      } else if (k === "pixelSpacing") {
        [columnPixelSpacing, rowPixelSpacing] = v.split("\\");
        isNaN(rowPixelSpacing) && (rowPixelSpacing = columnPixelSpacing)
      } else if (k === "rps") {
        rowPixelSpacing = v;
      } else if (k === "intercept") {
        intercept = v;
      } else if (k === "orientation") {
        orientation = v;
      } else if (k === "origin") {
        origins = v.split(",");
      } else if (k === "invert") {
        if (v === "undefined" || v === "false") {
          invert = false;
        } else if (v === "true") {
          invert = true;
        }
      }
    });
    let xhr = new XMLHttpRequest();
    xhr.timeout = 60000
    const promise = new Promise(function (resolve, reject) {
      xhr.open("get", url, true);
      xhr.responseType = "arraybuffer";
      xhr.onreadystatechange = function (oEvent) {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let responseAsArrayBuffer = xhr.response;
            let byteArray = new Int8Array(responseAsArrayBuffer);
            let png = UPNG.decode(byteArray);
            if (png.depth === 16) {
              png.data = u8tou16(png);
            }
            resolve(getImage(png));
            byteArray = null;
          } else {
            reject(xhr.statusText);
            //Message.closeAll();
            //Message.error("影像获取有误，请稍后再试！");
            console.log("download failed: " + xhr.statusText);
          }
        }
      };
      xhr.send();
    });
    const cancelFn = () => {
      xhr.abort();
    };
    return {
      promise,
      cancelFn,
    };

    function u8tou16(png) {
      //let start = new Date().getTime()
      let raw8bit = png.data;
      let len = png.height * png.width * 2;
      let buf = new ArrayBuffer(len); // 2 bytes for each char
      let bufView = new Int16Array(buf);
      let index = 0;
      min = bufView[0];
      max = bufView[0];
      for (let i = 0; i < len; i += 2) {
        let lower = raw8bit[i + 1];
        let upper = raw8bit[i];
        bufView[index] = lower + (upper << 8)// - 32768;
        bufView[index] < min ? (min = bufView[index]) : (min = min);
        //bufView[index] > max ? (max = bufView[index]) : (max = max);
        index++;
      }
      //减去最小值
      for (let j = 0; j < bufView.length; j++) {
        bufView[j] -= min;
      }
      min = bufView[0];
      max = bufView[0];
      for(let i = 0; i < bufView.length; i++){
        bufView[i] < min ? (min = bufView[i]) : (min = min);
        bufView[i] > max ? (max = bufView[i]) : (max = max);
      }
      intercept = 0;
      //console.log("Time:",new Date().getTime() - start)
      return bufView;
    }

    function getImage(png) {
      const width = png.width;
      const height = png.height;
      let image = {
        imageId: imageId
        /*.replace(/ww[^&]+(&)?/g, "")
        .replace(/wl[^&]+(&)?/g, "")
        .replace(/intercept[^&]+(&)?/g, "")
        .replace(/pixelSpacing[^&]+(&)?/g, "")
        .replace(/&$/g, "")*/,
        minPixelValue: 0,
        maxPixelValue: 255,
        slope: 1.0,
        intercept: 0,
        windowCenter: +wl,
        windowWidth: +ww,
        actualwindowCenter: +wl,
        actualwindowWidth: +ww,
        depth: png.depth,
        getPixelData: () => png.data,
        rows: height,
        columns: width,
        height: height,
        width: width,
        //color: false,
        columnPixelSpacing: +columnPixelSpacing,
        rowPixelSpacing: +rowPixelSpacing,
        sizeInBytes: width * height,
        invert: invert || false,
        colormap: 'gray'
      };
      if (png.depth === 16) {
        image.minPixelValue = +min;
        image.maxPixelValue = +max;
        image.intercept = +intercept;
        image.sizeInBytes = width * height * 2;
        image.windowCenter = +wl;
        image.windowWidth = +ww;
      }
      return image;
    }
  },
  myImageLoader(imageId) {
    let that = this;
    const width = 512;
    const height = 512;
    const numPixels = 100;
    let pixelData; //= new Uint16Array(numPixels);
    let index = 0;
    let canvas;
    let aaaimg;
    function getPixelData() {
      return pixelData;
    }
    function getCanvas() {
      return canvas;
    }
    function getImage() {
      return aaaimg;
    }
    let image = {
      imageId: imageId,
      minPixelValue: 0,
      maxPixelValue: 255,
      slope: 1.0,
      intercept: 0,
      windowCenter: 128,
      windowWidth: 256,
      render: cornerstone.renderWebImage, //   renderGrayscaleImage
      getPixelData: getPixelData,
      getCanvas: getCanvas,
      getImage: getImage,
      rows: height,
      columns: width,
      height: height,
      width: width,
      color: true,
      rgba: false,
      columnPixelSpacing: 1.0,
      rowPixelSpacing: 1.0,
      invert: false,
      sizeInBytes: width * height * 4,
    };
    return new Promise(function (resolve, reject) {
      let x1 = document.createElement("CANVAS");
      canvas = x1;
      let imgase = new Image();
      // imgase.crossorigin = 'anonymous';
      imgase.onload = function () {
        aaaimg = this;
        image.columns = image.width = this.width;
        image.rows = image.height = this.height;
        image.sizeInBytes = this.width * this.height * 4;
        x1.setAttribute("width", this.width);
        x1.setAttribute("height", this.height);
        let ctx = x1.getContext("2d");
        ctx.drawImage(this, 0, 0, this.width, this.height);
        let imageData = ctx.getImageData(0, 0, this.width, this.height).data;
        pixelData = imageData; // new Uint16Array(this.width * this.height*4);
        resolve(image);
      };
      image.onerror = function () {
        that.event._dispatch("ctcornerstone.imgloadError", {
          src: imgase.src,
        });
      };
      imgase.src = imageId.replace("myImageLoader:", "");
    });
  },
};

export { imageLoaders };
